package br.com.ca5.service.impl;

import java.util.List;

import org.apache.myfaces.custom.navmenu.NavigationMenuItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.com.ca5.dao.MenuDao;
import br.com.ca5.entity.Menu;
import br.com.ca5.entity.Usuario;
import br.com.ca5.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService {

	private MenuDao menuDao;

	public NavigationMenuItem[] buscarMenuPorUsuario(Usuario usuario) {
		List<Menu> listMenusPai = menuDao.buscaMenusPaiPorUsuario(usuario);
		NavigationMenuItem[] nMenuPai = montaMenuRecursivo(listMenusPai,
				usuario);

		return nMenuPai;
	}

	public NavigationMenuItem[] montaMenuRecursivo(List<Menu> listMenusPai,
			Usuario usuario) {
		NavigationMenuItem[] nMenuPai = new NavigationMenuItem[listMenusPai
				.size()];
		int cont = 0;
		for (Menu menuPai : listMenusPai) {
			nMenuPai[cont] = new NavigationMenuItem(menuPai.getNome(), menuPai
					.getUrl());
			List<Menu> listMenusFilhos = menuDao.buscaMenusFilhosPorUsuario(
					usuario, menuPai);
			if (!listMenusFilhos.isEmpty()) {
				nMenuPai[cont].setNavigationMenuItems(montaMenuRecursivo(
						listMenusFilhos, usuario));
			}
			cont++;
		}

		return nMenuPai;
	}

	public MenuDao getMenuDao() {
		return menuDao;
	}

	@Autowired
	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

}
